package com.yunmang.activity.qianshou;

import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.yunmang.R;
import com.yunmang.activity.BaseActivity;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.DeliverBean;
import com.yunmang.entity.ParameterEntity.PaisongNoBean;
import com.yunmang.entity.ParameterEntity.PaisongYesBean;
import com.yunmang.entity.ParameterEntity.PsSuccessBean;
import com.yunmang.entity.ParameterEntity.SignBean;
import com.yunmang.entity.ParameterEntity.UploadJsonBean;
import com.yunmang.entity.ParameterEntity.UploadSignBean;
import com.yunmang.entity.event.SignEvent;
import com.yunmang.http.HttpUtils;
import com.yunmang.utils.CommonUtils;
import com.yunmang.utils.DateUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/5/10.
 */
public class SignDetailActivity extends BaseActivity implements OnItemClickListener {
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.tv_start)
    TextView tvStart;
    @InjectView(R.id.tv_end)
    TextView tvEnd;
    @InjectView(R.id.tv_ship_name)
    TextView tvShipName;
    @InjectView(R.id.tv_ship_phone)
    TextView tvShipPhone;
    @InjectView(R.id.tv_hdbh)
    TextView tvHdbh;
    @InjectView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @InjectView(R.id.tv_goods_number)
    TextView tvGoodsNumber;
    @InjectView(R.id.tv_tifu)
    TextView tvTifu;
    @InjectView(R.id.tv_money)
    TextView tvMoney;
    @InjectView(R.id.tv_huokuan)
    TextView tvHuokuan;
    @InjectView(R.id.tv_collect_money)
    TextView tvCollectMoney;
    @InjectView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @InjectView(R.id.et_sign_name)
    EditText etSignName;
    @InjectView(R.id.et_identify)
    EditText etIdentify;
    @InjectView(R.id.tv_date)
    TextView tvDate;

    @InjectView(R.id.ll_ps)
    LinearLayout ll_ps;
    @InjectView(R.id.ll_sign)
    LinearLayout ll_sign;
    @InjectView(R.id.btn_sign)
    Button btnSign;
    @InjectView(R.id.btn_paisong)
    Button btnPaisong;
    @InjectView(R.id.tv_ps)
    TextView tvPs;
    @InjectView(R.id.et_shf)
    EditText etShf;
    @InjectView(R.id.et_notes)
    EditText etNotes;
    private int id, deliverId;//运单id
    private Subscriber<UploadSignBean> subscriber;
    private Subscriber<DeliverBean> deliverBeanSubscriber;
    private Subscriber<PsSuccessBean> psSuccessSubscriber;
    private List<DeliverBean.ModelBean> modelList;
    private List<String> deliverList;
    private String tag, method;
    private AlertView mAlertView;
    private PaisongYesBean psYesBean;
    private PaisongNoBean psNoBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_sign_detail;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        initToolbar();

    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("派送签收");
        mToolbar.setNavigationIcon(R.mipmap.ic_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public String fillJson() {
        UploadJsonBean bean = new UploadJsonBean();
        bean.setId(id);//运单id
        bean.setUserId(Integer.parseInt(AppConstant.userid));
        bean.setSignName("签收人");
        bean.setSignIDCardNumber("身份证");
        Gson gson = new Gson();
        Log.e("res", gson.toJson(bean).toString());
        return gson.toJson(bean).toString();
    }

    public void onEventMainThread(SignEvent event) {
        id=event.getId();
        method=event.getBalanceMethod();
//        tvStart.setText(event.getStartDepartName());
        tvStart.setText(event.getStartOrgName());
        tvEnd.setText(event.getEndOrgName());
        tvHdbh.setText(event.getHdbh());

        tvCollectMoney.setText(event.getGoodsCost()+"");
        tvGoodsName.setText(event.getGoodsName());
        tvGoodsNumber.setText(event.getNumbers()+"件");
        tvShipPhone.setText(event.getShipperPhone());
        tvShipName.setText(event.getShipper());
        tvTifu.setText(event.getBalanceMethod());
        tvMoney.setText(event.getTransportCost()+"");
        int status = event.getStatus();
        Log.e("result",event.getStartDepartName()+":"+event.getTransportCost()+":"+event.getNumbers());
        if (event.getTakeMethod().trim().equals("自提")) {
            ll_ps.setVisibility(View.GONE);
            ll_sign.setVisibility(View.VISIBLE);
            tvDate.setText(DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD));
            btnSign.setText("签收");
        } else {
            if(status==5){
                ll_ps.setVisibility(View.GONE);
                ll_sign.setVisibility(View.VISIBLE);
                tvDate.setText(DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD));
                btnSign.setText("签收");
            }else{
                ll_ps.setVisibility(View.VISIBLE);
                ll_sign.setVisibility(View.GONE);
                btnPaisong.setText("派送");
            }

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.btn_sign, R.id.btn_paisong, R.id.tv_ps})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_ps:
                requestDevliver();
                break;
            case R.id.btn_sign:
                showWaitingDialog("上传数据中……");
                subscriber = new Subscriber<UploadSignBean>() {
                    @Override
                    public void onCompleted() {
                        hideWaitingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitingDialog();
                    }

                    @Override
                    public void onNext(UploadSignBean uploadSignBean) {
                        hideWaitingDialog();
                        if (uploadSignBean.getCode() == 200) {
                            showToast("签收成功");
                            //需要finish掉页面并刷新
                            EventBus.getDefault().post("refresh");
                            finish();
                        } else {
                            showToast("签收失败");
                        }
                    }
                };
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), fillJson());
                HttpUtils.getInstance().uploadSignInfo(subscriber, body);
                break;
            case R.id.btn_paisong:
                String deliver = CommonUtils.getTextViewValue(tvPs);
                if (TextUtils.isEmpty(deliver)) {
                    showToast("请选择派送员");
                    return;
                }
                uploadDeliver();
                break;
        }
    }

    /**
     * 执行派送
     * 1.现付 不可以修改送货费
     * 2.到付 可以修改送货费
     */
    private void uploadDeliver() {
        showWaitingDialog("上传中……");
        psSuccessSubscriber = new Subscriber<PsSuccessBean>() {
            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                hideWaitingDialog();
                e.printStackTrace();
            }

            @Override
            public void onNext(PsSuccessBean psSuccessBean) {
                hideWaitingDialog();
                if(psSuccessBean.getCode()==200){
                    showToast("派送成功");
                }else{
                    showToast("派送失败");
                }
            }
        };
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),constructJson());
        Log.e("ps",constructJson());
        HttpUtils.getInstance().paisongAlert(psSuccessSubscriber,body);
    }

    private String constructJson() {
        Gson gson = new Gson();
        if (method.equals("提付")) {
            psYesBean = new PaisongYesBean();
            psYesBean.setUserHostAddress("mac地址");
            psYesBean.setNote("备注");
            psYesBean.setUserId(Integer.parseInt(AppConstant.userid));
            List<PaisongYesBean.BillListBean> billListBeanList = new ArrayList<>();
            PaisongYesBean.BillListBean bean = new PaisongYesBean.BillListBean();
            bean.setId(id);
            bean.setDeliveryCost(Double.valueOf(CommonUtils.getTextViewValue(etShf)));
            billListBeanList.add(bean);
            psYesBean.setBillList(billListBeanList);
            psYesBean.setDeliveryUserId(deliverId);
            return gson.toJson(psYesBean);
        } else {
            psNoBean = new PaisongNoBean();
            psNoBean.setUserHostAddress("mac地址");
            psNoBean.setNote("备注");
            psNoBean.setUserId(Integer.parseInt(AppConstant.userid));
            psNoBean.setDeliveryUserId(deliverId);
            List<Integer> billList = new ArrayList<>();
            billList.add(id);
            psNoBean.setBillIdList(billList);
            return gson.toJson(psNoBean);
        }
    }

    private void requestDevliver() {
        showWaitingDialog("加载中……");
        deliverBeanSubscriber = new Subscriber<DeliverBean>() {
            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                hideWaitingDialog();
                e.printStackTrace();
            }

            @Override
            public void onNext(DeliverBean deliverBean) {
                hideWaitingDialog();
                if (deliverBean.getCode() == 200) {
                    modelList = deliverBean.getModel();
                    fillData();
                } else {
                    showToast("下载失败");
                }
            }
        };
        HttpUtils.getInstance().getDeliver(deliverBeanSubscriber, AppConstant.orgInfo.getId() + "");
    }

    private void fillData() {
        if (modelList.size() == 0)
            return;
        deliverList = new ArrayList<>();
        for (DeliverBean.ModelBean bean : modelList) {
            deliverList.add(bean.getName());
        }
        String[] ss = new String[deliverList.size()];
        fillDeliver(deliverList.toArray(ss));
    }

    private void fillDeliver(String[] stringDeliver) {
        mAlertView = new AlertView(null, null, null, null, stringDeliver, this, AlertView.Style.Alert, this);
        mAlertView.show();
    }

    @Override
    public void onItemClick(Object o, int position) {
        if (o == mAlertView && position != AlertView.CANCELPOSITION) {
            tvPs.setText(modelList.get(position).getName());
            deliverId = modelList.get(position).getId();
        }
    }

}
